package com.ruoyi.system.outto.goods.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttrTemplateMapper;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttributeMapper;
import com.ruoyi.system.V2.gameAttr.service.IGameAttributeService;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoImgMapper;
import com.ruoyi.system.V2.inter.mapper.ArtRecMapper;
import com.ruoyi.system.interAttr.domain.InterAttr;
import com.ruoyi.system.interAttr.mapper.InterAttrMapper;
import com.ruoyi.system.model.domain.*;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.outto.dto.HttpUtil;
import com.ruoyi.system.outto.goods.DGGAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lz
 * @version 1.0
 * @date 2022/8/16 22:58
 */
@Slf4j
@Service
public class DGGApiImpl implements DGGAPI {

    @Resource
    private IGameAttributeService gameAttributeService;
    @Resource
    InterAttrMapper interAttrMapper;
    @Resource
    private GameAttributeMapper gameAttributeMapper;
    @Resource
    private GoodsInfoImgMapper goodsInfoImgMapper;
    @Resource
    private ArtRecMapper artRecMapper;
    @Resource
    private GameAttrTemplateMapper gameAttrTemplateMapper;


    @Override
    public AjaxResult addGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Map<String, Object> resultMap = new HashMap<>();

        Map<String, Object> params = params(goodsInfoAndAttrValueDto, salePartner);
        log.info("地瓜阁添加接口请求参数={}", JSONObject.toJSONString(params));
        Map<String, Object> header = new HashMap<>();
        header.put("token", salePartner.getSaleKey());
        String result = HttpUtils.doPostForm("https://external.dg66.com/api/addGoods", params, header);
        log.info("地瓜阁添加接口返回参数={}", result);
        JSONObject resultJson = JSONObject.parseObject(result);
        String data = resultJson.getString("data");
        if (!"200".equals(resultJson.getString("code"))) {
            resultMap.put("code", 500);
        } else {
            resultMap.put("code", 200);
            resultMap.put("outId", goodsInfoAndAttrValueDto.getId());
        }
        resultMap.put("req", JSONObject.toJSONString(params));
        resultMap.put("res", result);
        resultMap.put("msg", resultJson.getString("message"));

        return AjaxResult.success(resultMap);
    }

    @Override
    public AjaxResult editGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Map<String, Object> resultMap = new HashMap<>();

        Map<String, Object> params = params(goodsInfoAndAttrValueDto, salePartner);
        log.info("地瓜阁编辑接口请求参数={}", JSONObject.toJSONString(params));
        Map<String, Object> header = new HashMap<>();
        header.put("token", salePartner.getSaleKey());
        String result = HttpUtils.doPostForm("https://external.dg66.com/api/addGoods", params, header);
        log.info("地瓜阁编辑接口返回参数={}", result);

        JSONObject resultJson = JSONObject.parseObject(result);
        if (!"200".equals(resultJson.getString("code"))) {
            resultMap.put("code", 500);
        } else {
            resultMap.put("code", 200);
        }
        resultMap.put("req", JSONObject.toJSONString(params));
        resultMap.put("res", result);
        resultMap.put("msg", resultJson.getString("message"));

        return AjaxResult.success(resultMap);
    }

    @Override
    public AjaxResult delGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        params.put("userId", salePartner.getOther());
        ArtRec artRecreq = new ArtRec();
        artRecreq.setConfig(salePartner.getId());
        artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
        List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
        params.put("cid", artRecs.get(0).getOutid());
        log.info("地瓜阁删除接口请求参数={}", JSONObject.toJSONString(params));
        Map<String, Object> header = new HashMap<>();
        header.put("token", salePartner.getSaleKey());
        String result = HttpUtils.doPostForm("https://external.dg66.com/api/delGoods", params, header);
        log.info("地瓜阁删除接口返回参数={}", result);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!"200".equals(resultJson.getString("code"))) {
            resultMap.put("code", 500);
        } else {
            resultMap.put("code", 200);
        }
        resultMap.put("req", JSONObject.toJSONString(params));
        resultMap.put("res", result);
        resultMap.put("msg", resultJson.getString("message"));

        return AjaxResult.success(resultMap);
    }

    private Map<String, Object> params(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Map<String, Object> params = new TreeMap<>();
        params.put("userId", salePartner.getOther());
        ArtRec artRecreq = new ArtRec();
        artRecreq.setConfig(salePartner.getId());
        artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
        List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
        params.put("cid", CollectionUtils.isNotEmpty(artRecs) ? artRecs.get(0).getOutid() : goodsInfoAndAttrValueDto.getId());
        String title =  goodsInfoAndAttrValueDto.getDes().length()>199?goodsInfoAndAttrValueDto.getDes().substring(0,199):goodsInfoAndAttrValueDto.getDes();
        params.put("title",title.replace("+", ""));
        //属性匹配
        Property(goodsInfoAndAttrValueDto, params, salePartner);
        GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
        goodsInfoImg.setGoodsId(goodsInfoAndAttrValueDto.getId());
        goodsInfoImg.setType(Constants.STR_1);
        List<GoodsInfoImg> infoImgs = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);
        String imgUrls = infoImgs.stream().map(info -> info.getImgUrl()).collect(Collectors.toList()).stream().collect(Collectors.joining(","));
        params.put("images", imgUrls);
        params.put("account", goodsInfoAndAttrValueDto.getAccountNumber());
        params.put("password", String.valueOf(System.currentTimeMillis()));
        params.put("price", goodsInfoAndAttrValueDto.getPrice());
        params.put("phone", "18888888888");
        params.put("guarantee", "1");
        params.put("bargain", "1");

        return params;
    }
    private Map Property(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map params, SalePartner salePartner) {

        String substring = salePartner.getSaleName();
        if (substring.contains("_")) {
            substring = substring.substring(salePartner.getSaleName().indexOf("_")+1);
        }
        InterAttr interAttr = interAttrMapper.selectInterAttrByConfig(substring, goodsInfoAndAttrValueDto.getGameId());

        params.put("gameId", interAttr.getInterGameId());

        //开始匹配区服属性
        builderServer(goodsInfoAndAttrValueDto, params, interAttr.getServer());
        //开始匹配单选属性
        builderRadioAttr(goodsInfoAndAttrValueDto, params, interAttr.getRadioAttr());
        //开始匹配多选属性
        builderCheckAttr(goodsInfoAndAttrValueDto, params, interAttr.getCheckAttr());
        //开始匹配输入框属性
        builderInputAttr(goodsInfoAndAttrValueDto, params, interAttr.getInputAttr());
        return params;
    }

    private void builderInputAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map params, String inputAttr) {
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();

        //========================开始匹配输入框=====================//
        JSONObject jsonObject1 = JSONObject.parseObject(inputAttr);
        String inputJson = jsonObject1.getString("inputJson");
        List<JSONObject> jsonObjects1 = JSONObject.parseArray(inputJson, JSONObject.class);
        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        ArrayList types = new ArrayList<>();
        types.add("number");
        types.add("input");
        gameAttrTemplate.setFieldTypes(types);
        List<GameAttrTemplate> inputTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
        List<JSONObject> defInputObjects = new ArrayList<>();
        defInputObjects.addAll(jsonObjects1);
        for (JSONObject object : jsonObjects1) {
            for (GameAttrTemplate inputTemplate : inputTemplates) {
                String aavName = inputTemplate.getAavName();
                if (Objects.equals(object.getString("aavName"), inputTemplate.getAavName())) {
                    defInputObjects.remove(object);
                    String aavNameInter = object.getString("interName");
                    String interId = object.getString("interId");
                    for (Field declaredField : declaredFields) {
                        String name = declaredField.getName();
                        if (Objects.equals(aavName, name)) {
                            declaredField.setAccessible(true);
                            Object o = null;
                            try {
                                o = declaredField.get(goodsInfoAndAttrValueDto);
                            } catch (IllegalAccessException e) {
                                throw new GlobalException("3属性参数错误，请匹配后重新配置");
                            }
                            if(Objects.nonNull(o)) {
                                String oneValue = String.valueOf(o);
                                if (StringUtils.isNotEmpty(oneValue)) {
                                    params.put(interId,oneValue);
                                }
                            }else {
                                params.put(interId,0);
                            }
                        }
                    }
                }
            }
        }
        //开始匹配默认值
        for (JSONObject object : defInputObjects) {
            String id = object.getString("id");
            if(!id.equals("无一键匹配多选属性")) {
                params.put(id, 0);
            }
        }
    }

    private void builderCheckAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map params, String checkAttr) {
//        JSONArray propertys = Objects.isNull(params.get("property")) ? new JSONArray() : JSONArray.parseArray(params.get("property").toString());
        //========================开始匹配多选属性=====================//
        /**
         * 1、先查询自定义中所有多选的字段
         * 2、再查该账号单选字段中的选项
         * 3、再去接口属性匹配表过滤
         */
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();
        if(StringUtils.isNotEmpty(checkAttr)) {
            JSONObject checkAttrJson = JSONObject.parseObject(checkAttr);
            String interCheckBoxReqs = checkAttrJson.getString("interCheckBoxReqs");
            List<JSONObject> checkJsonList = JSONObject.parseArray(interCheckBoxReqs, JSONObject.class);
            if (org.springframework.util.CollectionUtils.isEmpty(checkAttrJson)) {
                throw new GlobalException("接口多选属性暂未配置");
            }

            GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
            gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
            gameAttrTemplate.setIsEnable("0");
            List<String> types = new ArrayList<>();
            types.add("checkbox");
            types.add("boxradio");
            gameAttrTemplate.setFieldTypes(types);
            List<GameAttrTemplate> checkAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
            String string = "";
            for (JSONObject object : checkJsonList) {
                for (GameAttrTemplate attrTemplate : checkAttrTemplates) {
                    String aavName = attrTemplate.getAavName();
                    for (Field declaredField : declaredFields) {
                        String name = declaredField.getName();
                        if (aavName.equals(name)) {
                            declaredField.setAccessible(true);

                            String ydConfigIdLeveOne = object.getString("YdConfigId");
                            if (StringUtils.isNotEmpty(ydConfigIdLeveOne)) {
                                String[] split2 = ydConfigIdLeveOne.split(",");
                                List<String> list2 = new ArrayList<>();
                                for (String s : split2) {
                                    s = s.replace(" ", "");
                                    list2.add(s);
                                }
                                if (list2.contains(attrTemplate.getId() + "")) {
                                    Object o = null;
                                    try {
                                        o = declaredField.get(goodsInfoAndAttrValueDto);
                                    } catch (IllegalAccessException e) {
                                        throw new GlobalException("多选项" + attrTemplate.getFieldName() + "匹配错误");
                                    }
                                    String oneValue = String.valueOf(o);
                                    //一级属性
                                    String ydConfigId = object.getString("YdConfigId");

                                    if (StringUtils.isNotEmpty(ydConfigId)) {
                                        ydConfigId = ydConfigId.replace(" ","");
                                        String[] split = ydConfigId.split(",");
                                        //一级属性已经匹配，开始匹配二级属性
                                        if (Arrays.asList(split).contains(attrTemplate.getId() + "")) {
                                            String interCheckBoxReqsStr = object.getString("interCheckBoxReqs");
//                                        String interCheckBoxReqsStr = object.getString("interServerRes");
                                            //开始匹配二级属性
                                            List<JSONObject> jsonObjects2 = JSONObject.parseArray(interCheckBoxReqsStr, JSONObject.class);
                                            /**
                                             * 咱们的f字段  多选项都是用空格 隔开，用,号切割数组，跟匹配的数据匹配、匹配上说明此账号勾选的有此属性
                                             */
//                                        List<String> list = new ArrayList<>();
                                            for (JSONObject jsonObject1 : jsonObjects2) {
                                                if (StringUtils.isNotEmpty(oneValue)) {
                                                    String[] split1 = oneValue.split(",");
                                                    String ydConfigId1 = jsonObject1.getString("YdConfigId");
                                                    for (String s : split1) {
                                                        if (Objects.equals(s, ydConfigId1)) {
                                                            String InterConfigId2 = jsonObject1.getString("InterConfigId");
                                                            string+=","+InterConfigId2;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    } else {
                                        throw new GlobalException("属性参数错误，请匹配后重新配置");
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if(StringUtils.isNotEmpty(string)) {
                params.put("roles", string.substring(1));
            }
            //========================多选属性匹配完成=====================//
        }
    }

    private void builderRadioAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map params, String radioAttr) {
        //========================开始匹配单选属性=====================//
        JSONObject jsonObject = JSONObject.parseObject(radioAttr);
        String interRadioReqs = jsonObject.getString("interRadioReqs");
        log.info(JSONObject.toJSONString(interRadioReqs));
        List<JSONObject> jsonObjects = JSONObject.parseArray(interRadioReqs, JSONObject.class);
        if (org.springframework.util.CollectionUtils.isEmpty(jsonObjects)) {
            throw new GlobalException("接口单选属性暂未配置");
        }
        /**
         * 1、先查询自定义中所有单选的字段
         * 2、再查该账号单选字段中的选项
         * 3、再去接口属性匹配表过滤
         */
        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        gameAttrTemplate.setFieldType("radio");
        List<GameAttrTemplate> gameAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();


        List<JSONObject> defObjects = new ArrayList<>();
        defObjects.addAll(jsonObjects);
        for (JSONObject object : jsonObjects) {
            for (GameAttrTemplate attrTemplate : gameAttrTemplates) {
                String aavName = attrTemplate.getAavName();
                for (Field declaredField : declaredFields) {
                    String name = declaredField.getName();
                    if (aavName.equals(name)) {
                        //一级属性
                        //注意 YdConfigId 对应的是 f字段对应的 id
                        if (Objects.equals(object.getLong("YdConfigId"), attrTemplate.getId())) {
                            String InterConfigId = object.getString("InterConfigId");
                            defObjects.remove(object);//如果匹配上，则去掉
                            String interRadioReqs1 = object.getString("interRadioReqs");
                            List<JSONObject> jsonObjects2 = JSONObject.parseArray(interRadioReqs1, JSONObject.class);
                            declaredField.setAccessible(true);
                            try {
                                //获取选择的值 例如  实名中的可二次
                                Object o = declaredField.get(goodsInfoAndAttrValueDto);
                                String oneValue = String.valueOf(o);
                                List<JSONObject> twoAttr = jsonObjects2.stream().filter(j -> StringUtils.isNotEmpty(j.getString("YdConfigId"))?j.getString("YdConfigId").contains(oneValue):"111".contains(oneValue)).collect(Collectors.toList());
                                String defaultValue = object.getString("defaultValue");
                                if (org.springframework.util.CollectionUtils.isEmpty(twoAttr)) {
                                    if (StringUtils.isNotEmpty(defaultValue)) {
                                        params.put(InterConfigId,defaultValue);
                                    }else {
                                        params.put(InterConfigId,jsonObjects2.get(0).getString("id"));
                                    }
                                }

                                if (!org.springframework.util.CollectionUtils.isEmpty(twoAttr)) {
                                    JSONObject jsonObject2 = twoAttr.get(0);
                                    String interConfigId2 = jsonObject2.getString("InterConfigId");
                                    params.put(InterConfigId,interConfigId2);
                                }
                            } catch (Exception e) {
                                throw new GlobalException("单选项" + attrTemplate.getFieldName() + "匹配错误");
                            }
                        }
                    }
                }
            }
        }
        //开始匹配默认值
        for (JSONObject object : defObjects) {
            String defaultValue = object.getString("defaultValue");
            interRadioReqs = object.getString("interRadioReqs");
            jsonObjects = JSONObject.parseArray(interRadioReqs, JSONObject.class);
            for (JSONObject objects : jsonObjects) {
                if(StringUtils.isNotEmpty(objects.getString("defaultValue"))){
                    params.put(defaultValue,objects.getString("defaultValue"));
                }
            }
        }
        //========================单选属性匹配结束=====================//
    }

    private void builderServer(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map params, String server) {
        //========================开始匹配区服属性=====================//
        JSONObject jsonObject = JSONObject.parseObject(server);
        //开始匹配一级区服
        String interServeReqs = jsonObject.getString("interServeReqs");
        String qufuid = "";
        List<JSONObject> oneServer = JSONObject.parseArray(interServeReqs, JSONObject.class);
        if (goodsInfoAndAttrValueDto.getGameType().equals("1")) {
            qufuid = goodsInfoAndAttrValueDto.getGroupId()+"";
            for (JSONObject object : oneServer) {
                String ydServeId = object.getString("YdServeId");
                if (StringUtils.isNotEmpty(ydServeId)) {
                    ydServeId = ydServeId.replace(",", "").replace(" ", "");
                    if (ydServeId.contains(qufuid)) {
                        String interServerRes = object.getString("interServerRes");
                        List<JSONObject> twoServer = JSONObject.parseArray(interServerRes, JSONObject.class);
                        for(JSONObject two:twoServer){
                            if(two.getString("YdServeId").replace(",", "").replace(" ", "").equals(qufuid)) {
                                params.put("areaId", object.getString("id"));
                                params.put("serverId", two.getString("id"));
                                break;
                            }
                        }
                    }
                }
            }
        } else if(goodsInfoAndAttrValueDto.getGameName().equals("原神")){
            qufuid = goodsInfoAndAttrValueDto.getCarrierId() + "";
        }else if (goodsInfoAndAttrValueDto.getGameName().equals("光遇")){
            qufuid = goodsInfoAndAttrValueDto.getSystemId().toString() + goodsInfoAndAttrValueDto.getCarrierId() + goodsInfoAndAttrValueDto.getGroupId() + goodsInfoAndAttrValueDto.getServerId();
        }else{
            qufuid = goodsInfoAndAttrValueDto.getSystemId() + "" + goodsInfoAndAttrValueDto.getCarrierId();
        }
        for (JSONObject object : oneServer) {
            String ydServeId = object.getString("YdServeId");
            if (StringUtils.isNotEmpty(ydServeId)) {
                ydServeId = ydServeId.replace(", ", "");
                if (Objects.equals(qufuid, ydServeId)) {
                    params.put("areaId", object.getString("InterServeId"));
                    break;
                }
            }
        }
    }

    private String reIds(String allIds, String ids) {
        if (StringUtils.isNotEmpty(ids)) {
            if (StringUtils.isNotEmpty(allIds)) {
                allIds = allIds + "," + ids;
            } else {
                allIds = ids;
            }
        }
        return allIds;
    }

    private List<GameAttribute> getGameAttributs(String ids) {
        if (StringUtils.isEmpty(ids)) {
            return new ArrayList<>();
        }
        return gameAttributeMapper.selectGameAttributeListByIds((Long[]) ConvertUtils.convert(ids.split(","),
                Long.class));
    }

    public static void main(String[] args) {

        //无畏契约 43
        Map<String, String> params = new HashMap<>();
//        params.put("gameId", "28");
//        String result = HttpUtil.doGet("https://external.dg66.com/game/listQt", params, null);
        String result = getProperty("22");
        log.info(result);
    }

    static String getGames() {
        Map<String, String> params = new HashMap<>();
        String result = HttpUtil.doGet("https://external.dg66.com/game/listQt", params, null);
        return result;
    }

    static String getProperty(String gameId) {
        Map<String, String> params = new HashMap<>();
        params.put("gameId", gameId);
        String result = HttpUtil.doGet("https://external.dg66.com/game/property", params, null);
        return result;
    }

    public static String getRole(String gameId) {
        Map<String, String> params = new HashMap<>();
        params.put("gameId", gameId);
        String result = HttpUtil.doGet("https://external.dg66.com/game/role", params, null);
        log.info(result);
        return result;
    }
    public static String getArea(String gameId){
        Map<String, String> params = new HashMap<>();
        params.put("gameId", gameId);

        String result = HttpUtil.doGet("https://external.dg66.com/game/system", params, null);
        log.info(result);
        return result;
    }

    public static String getArea(String gameId, String pid) {
        Map<String, String> params = new HashMap<>();
        params.put("gameId", gameId);
        if(StringUtils.isNotEmpty(pid)) {
            params.put("pid", pid);
        }
        String result = HttpUtil.doGet("https://external.dg66.com/game/system", params, null);
        log.info(result);
        return result;
    }

}
